package com.demo.security.handler.extract;

import com.demo.security.exceptions.JwtTokenAuthenticationException;
import com.demo.security.token.JwtToken;
import com.demo.security.token.Token;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * JWT 请求头拾取器,根据JWT的标准.TOKEN传入要以 Bearer + token的方式 传入
 * 这里对TOKEN获取并将token剥离出来返回进行分离
 * @author molong
 * @since 2024/5/24
 */
public class JwtHeaderTokenExtractor {

    private static final String HEADER_PREFIX = "Bearer ";
    private static final String JWT_TOKEN_HEADER_PARAM = "Authorization";
    private String tokenHeader = JWT_TOKEN_HEADER_PARAM;
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtHeaderTokenExtractor.class);

    public JwtHeaderTokenExtractor() {
        this(null);
    }

    private JwtHeaderTokenExtractor(String jwtTokenHeader) {
        if (StringUtils.isNotEmpty(jwtTokenHeader)) {
            tokenHeader = jwtTokenHeader;
        }
    }

    /**
     * 拾取request请求,获取规定的参数,并返回给调用方法
     *
     * @param request 当前http 请求
     * @return 返回泛型具体对象
     */
    public Token extract(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if (StringUtils.isBlank(token)) {
            LOGGER.debug("JWT token 不能为空! ");
            throw new JwtTokenAuthenticationException("Authorization header cannot be blank!");
        }
        if (token.length() <= HEADER_PREFIX.length()) {
            LOGGER.debug("Invalid token in request header! ");
            throw new JwtTokenAuthenticationException("Invalid authorization header size.");
        }
        String jwtToken = token.substring(HEADER_PREFIX.length());
        return new JwtToken(jwtToken);
    }
}
